import 'package:ball_lion/module/match_detail/live/live_plan_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/live/live_message_logic.dart';
import 'package:ball_lion/module/live/items/gift_bottom_sheet.dart';
import 'package:ball_lion/module/live/items/goods_bottom_sheet.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/ali_message.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'live_message_list.dart';

class LiveTextField extends GetView<LiveMessageLogic> {
  const LiveTextField(this.liveId,
      {super.key, this.sportsId = 1, required this.scene});

  final int liveId;
  final MessageScene scene;
  final int sportsId;

  @override
  String? get tag => "$liveId";

  @override
  Widget build(BuildContext context) {
    if (scene == MessageScene.push) return Container();
    return Stack(
      children: [
        Positioned.fill(
          child: AnimatedContainer(
              color: scene == MessageScene.match || controller.focus.hasFocus
                  ? Colours.white
                  : Colours.white.withOpacity(0),
              duration: const Duration(milliseconds: 300)),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (controller.chatInfo?.messages.hasValue == true &&
                ((controller.chatInfo?.open == true &&
                        controller.focus.hasFocus) ||
                    controller.chatInfo?.open == false) &&
                scene == MessageScene.match)
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                        children: controller.chatInfo?.messages
                                ?.split(",")
                                .map<Widget>((e) => GestureDetector(
                                      onTap: () => controller.sendChat(text: e),
                                      child: Container(
                                        height: 28,
                                        alignment: Alignment.center,
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 8),
                                        decoration: BoxDecoration(
                                            border: Border.all(
                                                color: Colours.grey99,
                                                width: 0.5),
                                            borderRadius:
                                                BorderRadius.circular(26)),
                                        child: QsText(e,
                                            needCenter: true,
                                            color: Colours.grey66),
                                      ),
                                    ))
                                .toList()
                                .insertEvery(Container(width: 8))
                                .insertWith(0, [Container(width: 8)]).append(
                                    Container(width: 8)) ??
                            [])
                    .paddingOnly(top: 8),
              ),
            Row(
              children: [
                Expanded(
                  child: LayoutBuilder(
                    builder: (context, cons) => GestureDetector(
                      child: AnimatedContainer(
                        height: 36,
                        width: cons.maxWidth,
                        duration: const Duration(milliseconds: 150),
                        margin: const EdgeInsets.fromLTRB(8, 8, 8, 8),
                        child: TextField(
                          key: ValueKey(liveId),
                          controller: controller.textController,
                          maxLines: 1,
                          focusNode: controller.focus,
                          onTapAlwaysCalled: false,
                          style: TextStyle(
                              fontSize: 14,
                              color: scene == MessageScene.match ||
                                      controller.focus.hasFocus
                                  ? Colours.text
                                  : Colours.white.withOpacity(0.5)),
                          strutStyle: const StrutStyle(fontSize: 16),
                          cursorColor: Colours.main,
                          readOnly: controller.chatInfo?.open != true,
                          onTap: () async {
                            if (controller.chatInfo?.barrage != true) {
                              Toast.text("当前直播间已禁言");
                              FocusScope.of(context).requestFocus(FocusNode());
                              return;
                            }
                            if (controller.chatInfo?.open != true) {
                              Toast.text("仅支持固定内容发布");
                              controller.focus.unfocus();
                            } else {
                              if (User.isLogin) {
                                Utils.onEvent(
                                    scene == MessageScene.normal
                                        ? 'spzb'
                                        : 'hpzb',
                                    params: {
                                      (scene == MessageScene.normal
                                          ? 'spzb'
                                          : 'hpzb'): 'zbpl'
                                    });
                                controller.focus.requestFocus();
                              } else {
                                controller.focus.unfocus();
                                var result = await Get.dialog(
                                    const QsDialog.alert("登录后才可评论，要去登录吗？",
                                        confirmText: "去登录"));
                                if (result == true) {
                                  await User.needLogin(() {
                                    AliMessage().enterGroup(
                                        controller.liveDetail?.chatGroupId ??
                                            "");
                                    controller.userStore = User.info;
                                  });
                                }
                              }
                            }
                          },
                          onChanged: (str) {
                            if (str.length > 50) {
                              Toast.text("发布内容不能多于50个字");
                              controller.str = str.substring(0, 50);
                            } else {
                              controller.str = str;
                            }
                            controller.textController.text = controller.str;
                          },
                          textInputAction: TextInputAction.send,
                          keyboardType: TextInputType.text,
                          onSubmitted: (str) {
                            if (str.noValue) {
                              Toast.text("发言内容不能为空");
                              return;
                            }
                            controller.sendChat();
                            controller.textController.clear();
                            controller.str = "";
                            controller.focus.unfocus();
                          },
                          onTapOutside: (event) {
                            if (controller.chatInfo?.messages.hasValue ==
                                    true &&
                                event.position.dy > 430 &&
                                scene == MessageScene.match) {
                            } else {
                              controller.focus.unfocus();
                            }
                          },
                          decoration: InputDecoration(
                              isDense: true,
                              filled: true,
                              isCollapsed: true,
                              fillColor: scene == MessageScene.match ||
                                      controller.focus.hasFocus
                                  ? Colours.greyF2F3F7
                                  : Colours.black.withOpacity(0.2),
                              contentPadding: const EdgeInsets.only(
                                  top: 8, bottom: 8, left: 2, right: 2),
                              prefixIcon: controller.focus.hasFocus
                                  ? null
                                  : Container(
                                      width: 24,
                                      padding: const EdgeInsets.only(left: 8),
                                      alignment: Alignment.center,
                                      child: Image.asset(
                                          Utils.getImgPath("comment_icon.png"),
                                          color: Colours.grey99,
                                          width: 14,
                                          height: 14),
                                    ),
                              prefixIconConstraints: const BoxConstraints(),
                              border: const OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                  borderRadius: BorderRadius.all(
                                      Radius.circular(35 / 2))),
                              counterText: "",
                              hintText: controller.chatInfo?.tip ?? "",
                              hintStyle: TextStyle(
                                  fontSize: 14,
                                  height: 1.7,
                                  color: scene == MessageScene.match ||
                                          controller.focus.hasFocus
                                      ? Colours.grey99
                                      : Colours.white.withOpacity(0.5))),
                        ),
                      ),
                    ),
                  ),
                ),
                if (!controller.focus.hasFocus) ...[
                  if (controller.chatInfo?.goods ?? false)
                    item("live_goods_icon.png", onTap: () {
                      Utils.onEvent("liveroom_ai_enter");
                      Get.bottomSheet(GoodsBottomSheet(liveId: liveId),
                          isScrollControlled: true,
                          ignoreSafeArea: false,
                          barrierColor: Colours.transparent);
                    }),
                  if (controller.chatInfo?.plan ?? false)
                    item("live_plan_icon.png", onTap: () {
                      Utils.onEvent("liveroom_plan_enter");
                      Get.bottomSheet(
                          LivePlanView(
                              info: controller.liveDetail, sportsId: sportsId),
                          isScrollControlled: true,
                          ignoreSafeArea: false,
                          barrierColor: Colours.transparent);
                    }),
                  if (controller.chatInfo?.gift ?? false)
                    item("live_gifts_icon.png",
                        onTap: () => User.needLogin(() {
                              Utils.onEvent("liveroom_gift_enter");
                              Get.bottomSheet(GiftBottomSheet(liveId: liveId),
                                  isScrollControlled: true,
                                  ignoreSafeArea: false,
                                  barrierColor: Colours.transparent);
                            }))
                ]
              ],
            ),
          ],
        ),
      ],
    );
  }

  Widget item(String icon, {Function()? onTap}) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.only(right: 8),
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: scene == MessageScene.match
                ? null
                : Colours.black.withOpacity(0.2)),
        child: Image.asset(Utils.getImgPath(icon), width: 24, height: 24),
      ),
    );
  }
}
